#!/usr/bin/perl

use locale;

open (PHONES, "$ARGV[0]") or die "Can't open phone set $ARGV[0]!\n$!\n";

print "# Substitutionen\n#\n";
while (<PHONES>) {
  chomp;
  ($phone, $maptarget) = split;
  push @phones, $phone;
  $phone =~ s/\\//g;
  $maptarget =~ s/\\//g;
  $map{$phone}=$maptarget;
  #in $map{$phone} steht das Mapping
  print "# $phone -> $maptarget\n";
}
close PHONES;

@phones = sort(@phones);
@phones = reverse(@phones);

$regex = "(_";
foreach $phone (@phones) {
  $regex = $regex . "|" .  $phone;
}
$regex = $regex . ")";
print "#Regexp dazu ist: $regex \n";

#Phone-Splitting mit Whitespace
while (<STDIN>) {
  chomp;
  ($orth, $type, $trans) = split;
  #Akzente und Silbengrenzen entfernen
  $trans =~ s/(\'|\||\,)//g;
  #Splitting
  $trans =~ s/$regex/$1 /g;
  $lex{uc($orth)}=$trans; 
  #in $lex{$orth} steht die alte Aussprache zu $orth
}

#Mapping und Ausgabe
no locale;
foreach $orth (sort keys %lex) {
  print "# $orth\t$lex{$orth}\n";
  print $orth , "\t";
  (@wordtrans) = split(/\s/, $lex{$orth});
  #$trans = $lex{$orth};
  $trans = "";
  foreach $phone (@wordtrans) {
    $trans = $trans . $map{$phone} . " ";
  }
  $trans =~ s/\s+$//g;
  print "$trans\n";
}
